package com.silence.gankio.core.net;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

import java.util.concurrent.TimeUnit;

/**
 * @author Silence
 */
public class RetryWithDelay implements Function<Observable<? extends Throwable>, Observable<?>> {

    private final int maxRetries;
    private final int retryDelay;
    private int retryCount;

    public RetryWithDelay(int maxRetries, int retryDelay) {
        this.maxRetries = maxRetries;
        this.retryDelay = retryDelay;
    }



    @Override
    public Observable<?> apply(Observable<? extends Throwable> observable) {
        return observable
                .flatMap(new Function<Throwable, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(Throwable throwable) {
                        if (++retryCount <= maxRetries) {
                            return Observable.timer(retryDelay,
                                    TimeUnit.SECONDS);
                        }
                        return Observable.error(throwable);
                    }
                });
    }
}
